<?php

/**
 * This is the shortcut to DIRECTORY_SEPARATOR
 */
defined('DS') or define('DS',DIRECTORY_SEPARATOR);
define('TIME', time());

/**
 * This is the shortcut to Yii::app()
 */
function app()
{
    return Yii::app();
}

/**
 * This is the shortcut to Yii::app()->clientScript
 */
function cs()
{
    // You could also call the client script instance via Yii::app()->clientScript
    // But this is faster
    return Yii::app()->getClientScript();
}

/**
 * This is the shortcut to Yii::app()->user.
 */
function user()
{
    return Yii::app()->getUser();
}

function userDisplayName($user = null) {
	if ( empty($user) ) return '(empty)';

	$display_name = $user->email;
	if ( !empty($user->firstname) ) {
		$display_name = $user->firstname;
	} elseif ( !empty($user->name) ) {
		$display_name = $user->name;
	} elseif ( !empty($user->user_login) ) {
		$display_name = $user->user_login;
	}

	return CHtml::encode($display_name);
}

function userDisplayNameArr($user = null) {
	if ( empty($user) ) return '(empty)';

	$display_name = $user['email'];
	if ( !empty($user['firstname']) ) {
		$display_name = $user['firstname'];
	} elseif ( !empty($user['user_login']) ) {
		$display_name = $user['user_login'];
	}

	return $display_name;
}

/**
 * This is the shortcut to Yii::app()->createUrl()
 */
function url($route,$params=array(),$ampersand='&')
{
    return Yii::app()->createUrl($route,$params,$ampersand);
}

/**
 * This is the shortcut to CHtml::encode
 */
function h($text)
{
    return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
}

/**
 * This is the shortcut to CHtml::link()
 */
function l($text, $url = '#', $htmlOptions = array())
{
    return CHtml::link($text, $url, $htmlOptions);
}

function img($object_type, $src, $alt, $htmlOptions, $size = 'full', $return_url = false, $lazy = true)
{
	try
	{
		$max_dim = 2000;

		$path = Yii::getPathOfAlias('file') . '/';
		$url = Yii::app()->params['frontUrl'] . 'files/';
	
		if ( !file_exists("{$path}{$object_type}/$src") ) {
			if ( file_exists("{$path}{$object_type}/no_image.png") ) {
				return img($object_type, 'no_image.png', $alt, $htmlOptions, $size, $return_url);
			} else {
				return '';
			}
		}
		
		if ( $size == 'full' ) {
			if ( $return_url ) {
				return "$url/$object_type/$src";
			}
			return CHtml::image($url."/$object_type/".$src, $alt, $htmlOptions);
		} else {
			$width = isset($size['width']) ? $size['width'] : $max_dim;
			$height = isset($size['height']) ? $size['height'] : $max_dim;
	
			$image_name = basename($src);
			$safe_image_name = safe_file_name($image_name);
			$new_image_name = ($width==$max_dim?'0':$width).'x'.($height==$max_dim?'0':$height).'-'.$safe_image_name;
			$thumbnail_folder = "thumbnail/".($width==$max_dim?'0':$width).'/'.($height==$max_dim?'0':$height);
			$thumbnail_path = "{$path}{$thumbnail_folder}";
			if ( !file_exists($thumbnail_path) ) mkdir($thumbnail_path, 0777, true);
	
			if ( !file_exists("$thumbnail_path/$new_image_name") ) {
				if ( $size == 'full' ) {
					@copy("{$path}{$object_type}/".$src, "$thumbnail_path/$new_image_name");
				} else {
					$image = Yii::app()->image->load("{$path}{$object_type}/$src");
					$image->resize($width, $height)->quality(100);
					$image->save("$thumbnail_path/$new_image_name");
				}
			}
	
			if ( $return_url ) {
				return "{$url}{$thumbnail_folder}/{$new_image_name}";
			}
			if($lazy)
			{
				//Using lazy loading here
				$src = "{$url}{$thumbnail_folder}/{$new_image_name}";
				$default_src = tu()."/images/no_image.png";
				$htmlOptions['data-src'] = $src;
				$htmlOptions['width'] = (!empty($width)) ? $width : "100%";
				$htmlOptions['height'] = (!empty($height)) ? $height : "100%";
				$htmlOptions['class'] = (!empty($htmlOptions['class'])) ?   "lazy item-lazy-imge ". $htmlOptions['class'] : "lazy item-lazy-image";
				//Send image to client
				return CHtml::image($default_src, $alt, $htmlOptions);
			}
			else {
				return CHtml::image("{$url}{$thumbnail_folder}/{$new_image_name}", $alt, $htmlOptions);
			}
		}
	}
	catch(Exception $ex)
	{
		return img($object_type, 'no_image.png', $alt, $htmlOptions, $size, $return_url);
	}
}

function img_crop($object_type, $src, $x, $y, $w, $h) {
	$upload_base_path = Image::getUploadBasePath($object_type);
	$upload_path = Image::getUploadPath($object_type);
	
	$image_name = basename($src);
	$safe_image_name = safe_file_name($image_name);
	$new_image_name = ($w).'x'.($h).'-'.$safe_image_name;
	
	$image_file = $upload_path . '/' . $new_image_name;
	$image_path = str_replace($upload_base_path, '', $image_file);
		
	if ( !file_exists($image_file) ) {
		$image = Yii::app()->image->load("{$upload_base_path}/".$src);
		$image->crop($w, $h, $y, $x)->quality(100);
		$image->save($image_file);
	}
	
	return $image_path;
}

function safe_file_name($filename) {
	$dot_pos = strrpos($filename, '.');
	$name_only = substr($filename, 0, $dot_pos);
	$extension = substr($filename, $dot_pos + 1);
	$safe_name = SiteHelper::generateSeoName($name_only);

	return $safe_name.'.'.$extension;

}

/**
 * This is the shortcut to Yii::t() with default category = 'stay'
 */
function t($message, $category = 'app', $params = array(), $source = null, $language = null)
{
    return Yii::t($category, $message, $params, $source, $language);
}

/**
 * This is the shortcut to Yii::app()->request->baseUrl
 * If the parameter is given, it will be returned and prefixed with the app baseUrl.
 */
function bu($url=null)
{
    static $baseUrl;
    if ($baseUrl===null)
        $baseUrl=Yii::app()->getRequest()->getBaseUrl();
    return $url===null ? $baseUrl : $baseUrl.'/'.ltrim($url,'/');
}

function tu($url=null) {
	static $themeUrl;
	if ($themeUrl===null)
        $themeUrl=Yii::app()->getTheme()->getBaseUrl();
	return $url===null ? $themeUrl : $themeUrl.'/'.ltrim($url,'/');
}

/**
 * Returns the named application parameter.
 * This is the shortcut to Yii::app()->params[$name].
 */
function param($name)
{
    return Yii::app()->params[$name];
}

function getParam($name, $default = null) {
	return trim(Yii::app()->request->getParam($name, $default));
}

function getQuery($name, $default = null) {
	return Yii::app()->request->getQuery($name, $default);
}

function getPost($name, $default = null) {
	return Yii::app()->request->getPost($name, $default);
}

function isAjaxRequest() {
	return Yii::app()->request->isAjaxRequest || getParam('is_ajax');
}

function getItemsPerPage() {
	return param('itemsPerPage');
}
function logInfo($message)
{
	Yii::log("$message", 'info', 'system');
}
/* DATETIME */
function parseDate($date, $default = null) {
	if ( $default === null ) $default = time();

	$timestamp = CDateTimeParser::parse($date, app()->params['altDateFormat']);
	return $timestamp ? $timestamp : $default;
}

function parseLongDate($date, $default = null) {
	if ( $default === null ) $default = time();

	$timestamp = CDateTimeParser::parse($date, app()->params['altLongDateFormat']);
	return $timestamp ? $timestamp : $default;
}

function formatDate($timestamp) {
	if ( $timestamp == 0 ) return '';
	return Yii::app()->dateFormatter->format(app()->params['altDateFormat'], $timestamp);
}

function formatLongDate($timestamp) {
	if ( $timestamp == 0 ) return '';
	return Yii::app()->dateFormatter->format(app()->params['altLongDateFormat'], $timestamp);
}

function formatWYSIWYG($content) {
	// replace image src url
	$content = str_replace('src="download/', 'src="'.param('frontUrl'). 'download/', $content);
	$content = str_replace('src="files/', 'src="'.param('frontUrl'). 'files/', $content);

	return $content;
}
     
/* STATIC GLOBAL VARIABLES */
function var_global($name, $value = null) {
	static $__var_globals;

	if ( $value ) {
		$__var_globals[$name] = $value;
	} elseif ( isset($__var_globals[$name]) ) {
		return $__var_globals[$name];
	}

	return null;
}
  

/* PRICE */
function formatPrice($value, $append_currency = false) {
	$price = number_format($value, param('currency_decimals'), param('decimalPoint'), param('thousandsSeparator'));

	if ( $append_currency )
		$price .= ' ' . param('currency');

	return $price;
}

/* MISC */
function createPeriods($params)
{
	$today = getdate(TIME);
	$period = !empty($params['period']) ? $params['period'] : null;

	$time_from = !empty($params['time_from']) ? parseDate($params['time_from']) : 0;
	$time_to = !empty($params['time_to']) ? parseDate($params['time_to']) : TIME;

	// Current dates
	if ($period == 'D') {
		$time_from = mktime(0, 0, 0, $today['mon'], $today['mday'], $today['year']);
		$time_to = TIME;

	} elseif ($period == 'W') {
		$wday = empty($today['wday']) ? "6" : (($today['wday'] == 1) ? "0" : $today['wday'] - 1);
		$wstart = getdate(strtotime("-$wday day"));
		$time_from = mktime(0, 0, 0, $wstart['mon'], $wstart['mday'], $wstart['year']);
		$time_to = TIME;

	} elseif ($period == 'M') {
		$time_from = mktime(0, 0, 0, $today['mon'], 1, $today['year']);
		$time_to = TIME;

	} elseif ($period == 'Y') {
		$time_from = mktime(0, 0, 0, 1, 1, $today['year']);
		$time_to = TIME;

	// Last dates
	} elseif ($period == 'LD') {
		$today = getdate(strtotime("-1 day"));
		$time_from = mktime(0, 0, 0, $today['mon'], $today['mday'], $today['year']);
		$time_to = mktime(23, 59, 59, $today['mon'], $today['mday'], $today['year']);

	} elseif ($period == 'LW') {
		$today = getdate(strtotime("-1 week"));
		$wday = empty($today['wday']) ? 6 : (($today['wday'] == 1) ? 0 : $today['wday'] - 1);
		$wstart = getdate(strtotime("-$wday day", mktime(0, 0, 0, $today['mon'], $today['mday'], $today['year'])));
		$time_from = mktime(0, 0, 0, $wstart['mon'], $wstart['mday'], $wstart['year']);

		$wend = getdate(strtotime("+6 day", $time_from));
		$time_to = mktime(23, 59, 59, $wend['mon'], $wend['mday'], $wend['year']);

	} elseif ($period == 'LM') {
		$today = getdate(strtotime("-1 month"));
		$time_from = mktime(0, 0, 0, $today['mon'], 1, $today['year']);
		$time_to = mktime(23, 59, 59, $today['mon'], date('t', strtotime("-1 month")), $today['year']);

	} elseif ($period == 'LY') {
		$today = getdate(strtotime("-1 year"));
		$time_from = mktime(0, 0, 0, 1, 1, $today['year']);
		$time_to = mktime(23, 59, 59, 12, 31, $today['year']);

	// Last dates
	} elseif ($period == 'HH') {
		$today = getdate(strtotime("-23 hours"));
		$time_from = mktime($today['hours'], $today['minutes'], $today['seconds'], $today['mon'], $today['mday'], $today['year']);
		$time_to = TIME;

	} elseif ($period == 'HW') {
		$today = getdate(strtotime("-6 day"));
		$time_from = mktime($today['hours'], $today['minutes'], $today['seconds'], $today['mon'], $today['mday'], $today['year']);
		$time_to = TIME;

	} elseif ($period == 'HM') {
		$today = getdate(strtotime("-29 day"));
		$time_from = mktime($today['hours'], $today['minutes'], $today['seconds'], $today['mon'], $today['mday'], $today['year']);
		$time_to = TIME;

	} elseif ($period == 'HC') {
		$today = getdate(strtotime('-' . $params['last_days'] . ' day'));
		$time_from = mktime($today['hours'], $today['minutes'], $today['seconds'], $today['mon'], $today['mday'], $today['year']);
		$time_to = TIME;
	}

	return array($time_from, $time_to);
}

function toggleClass($class, $on_class = 'odd', $off_class = 'even') {
	return $class == $on_class ? $off_class : $on_class;
}
function getCatLevel($id_path) {
	$count = explode('/', $id_path);

	return count($count) - 1;
}

function percentage($n, $m, $round = 0, $sign = '%')
{
	if ( $m == 0 ) return 0 . $sign;
	return round(($n / $m) * 100, $round) . $sign;
}

function shortenText($text, $len, $suffix = '...') {
	if ( strlen($text) < $len ) return $text;

	$text = $text." ";
	$text = substr($text, 0, $len);
	$text = substr($text, 0, strrpos($text, ' '));
	$text = $text.$suffix;
	return $text;
}

function formatDescription($text) {
	
	$text = preg_replace('%<p([^>]+)?>((&nbsp;)+|\s+)?</p>%i', '', $text);
	
	return $text;
}

function fn_crc32($key)
{
	return sprintf('%u', crc32($key));
}

function selected($value, $data = null, $echo = true) {
	$selected = '';

	if ( ($data === null && $value) || $value == $data ) {
		$selected = 'selected="selected"';
	}

	if ( $echo )
		echo $selected;

	return $selected;
}

function add_query_arg() {
	$ret = '';
	$args = func_get_args();
	if ( is_array( $args[0] ) ) {
		if ( count( $args ) < 2 || false === $args[1] )
			$uri = $_SERVER['REQUEST_URI'];
		else
			$uri = $args[1];
	} else {
		if ( count( $args ) < 3 || false === $args[2] )
			$uri = $_SERVER['REQUEST_URI'];
		else
			$uri = $args[2];
	}

	if ( $frag = strstr( $uri, '#' ) )
		$uri = substr( $uri, 0, -strlen( $frag ) );
	else
		$frag = '';

	if ( 0 === stripos( $uri, 'http://' ) ) {
		$protocol = 'http://';
		$uri = substr( $uri, 7 );
	} elseif ( 0 === stripos( $uri, 'https://' ) ) {
		$protocol = 'https://';
		$uri = substr( $uri, 8 );
	} else {
		$protocol = '';
	}

	if ( strpos( $uri, '?' ) !== false ) {
		list( $base, $query ) = explode( '?', $uri, 2 );
		$base .= '?';
	} elseif ( $protocol || strpos( $uri, '=' ) === false ) {
		$base = $uri . '?';
		$query = '';
	} else {
		$base = '';
		$query = $uri;
	}

	_parse_str( $query, $qs );
//	$qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
	if ( is_array( $args[0] ) ) {
		$kayvees = $args[0];
		$qs = array_merge( $qs, $kayvees );
	} else {
		$qs[ $args[0] ] = $args[1];
	}

	foreach ( $qs as $k => $v ) {
		if ( $v === false )
			unset( $qs[$k] );
	}

	$ret = http_build_query( $qs );
	$ret = trim( $ret, '?' );
	$ret = preg_replace( '#=(&|$)#', '$1', $ret );
	$ret = $protocol . $base . $ret . $frag;
	$ret = rtrim( $ret, '?' );
	return $ret;
	
}

function stripslashes_deep($value) {
	if ( is_array($value) ) {
		$value = array_map('stripslashes_deep', $value);
	} elseif ( is_object($value) ) {
		$vars = get_object_vars( $value );
		foreach ($vars as $key=>$data) {
			$value->{$key} = stripslashes_deep( $data );
		}
	} elseif ( is_string( $value ) ) {
		$value = stripslashes($value);
	}

	return $value;
}

function urlencode_deep($value) {
	$value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
	return $value;
}

function _parse_str( $string, &$array ) {
	parse_str( $string, $array );
	if ( get_magic_quotes_gpc() )
		$array = stripslashes_deep( $array );
}

function getDateOptions($type = 'Y') {
	$options = array();
	
	switch($type) {
		case 'Y':
			$cur_year = (int) date('Y');
			for ($i = 1940; $i <= $cur_year; $i++) {
				$options[$i] = sprintf('%s', $i);
			}
			break;
		
		case 'm':
			for ($i = 1; $i <= 12; $i++) {
				$options[$i] = sprintf('%s %d', t('Tháng'), $i);
			}
			break;
		
		case 'd':
			for ($i = 1; $i <= 31; $i++) {
				$options[$i] = sprintf('%s', $i);
			}
			break;
	}
	
	return $options;
}

/* SERIALIZE FUNCTIONS SET */
function maybe_unserialize( $original ) {
	if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
		return @unserialize( $original );
	return $original;
}

function is_serialized( $data, $strict = true ) {
	// if it isn't a string, it isn't serialized
	if ( ! is_string( $data ) )
		return false;
	$data = trim( $data );
 	if ( 'N;' == $data )
		return true;
	$length = strlen( $data );
	if ( $length < 4 )
		return false;
	if ( ':' !== $data[1] )
		return false;
	if ( $strict ) {
		$lastc = $data[ $length - 1 ];
		if ( ';' !== $lastc && '}' !== $lastc )
			return false;
	} else {
		$semicolon = strpos( $data, ';' );
		$brace     = strpos( $data, '}' );
		// Either ; or } must exist.
		if ( false === $semicolon && false === $brace )
			return false;
		// But neither must be in the first X characters.
		if ( false !== $semicolon && $semicolon < 3 )
			return false;
		if ( false !== $brace && $brace < 4 )
			return false;
	}
	$token = $data[0];
	switch ( $token ) {
		case 's' :
			if ( $strict ) {
				if ( '"' !== $data[ $length - 2 ] )
					return false;
			} elseif ( false === strpos( $data, '"' ) ) {
				return false;
			}
			// or else fall through
		case 'a' :
		case 'O' :
			return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
		case 'b' :
		case 'i' :
		case 'd' :
			$end = $strict ? '$' : '';
			return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
	}
	return false;
}

function is_serialized_string( $data ) {
	// if it isn't a string, it isn't a serialized string
	if ( !is_string( $data ) )
		return false;
	$data = trim( $data );
	$length = strlen( $data );
	if ( $length < 4 )
		return false;
	elseif ( ':' !== $data[1] )
		return false;
	elseif ( ';' !== $data[$length-1] )
		return false;
	elseif ( $data[0] !== 's' )
		return false;
	elseif ( '"' !== $data[$length-2] )
		return false;
	else
		return true;
}

function maybe_serialize( $data ) {
	if ( is_array( $data ) || is_object( $data ) )
		return serialize( $data );

	// Double serialization is required for backward compatibility.
	// See http://core.trac.wordpress.org/ticket/12930
	if ( is_serialized( $data, false ) )
		return serialize( $data );

	return $data;
}

/* TIME DIFF */
function getTimeDiff($time1, $time2, $precision = 2) {

	if (!is_int($time1)) {
		$time1 = strtotime($time1);
	}
	if (!is_int($time2)) {
		$time2 = strtotime($time2);
	}

	if ($time1 > $time2) {
		list( $time1, $time2 ) = array($time2, $time1);
	}

	$intervals = array('năm', 'tháng', 'ngày', 'giờ', 'phút', 'giây');
	$diffs = array();

	foreach ($intervals as $interval) {
		$ttime = strtotime('+1 ' . $interval, $time1);
		$add = 1;
		$looped = 0;
		while ($time2 >= $ttime) {
			$add++;
			$ttime = strtotime("+" . $add . " " . $interval, $time1);
			$looped++;
		}

		$time1 = strtotime("+" . $looped . " " . $interval, $time1);
		$diffs[$interval] = $looped;
	}

	$count = 0;
	$times = array();
	foreach ($diffs as $interval => $value) {
		if ($count >= $precision) {
			break;
		}
		if ($value > 0) {
			if ($value != 1) {
				$interval .= "s";
			}
			$times[] = $value . " " . $interval;
			$count++;
		}
	}

	return implode(", ", $times);
}

//Thoi gian cache cac item tren toan he thong.
define('CACHE_TIME', 0);

function compactor()
{
	//checking for d-o-m-a-i-n.
	$host = $_SERVER['HTTP_HOST'];
    return array(
        array(
            'common.extensions.compactor.ECompressHtmlFilter',
            'gzip'            => false, //Set to false if PHP.INI already openned gzip
            'doStripNewlines' => false,
            'actions' => '*'
        ),
    );
}